<?php

namespace app\admin\logic;

use app\admin\model\CompanyUser;
use app\common\exception\ApiException;
use app\common\model\Company;
use app\common\model\MessageNotification;
use app\common\model\MessageNotificationCompany;
use app\common\model\MessageNotificationRead;
use app\common\model\MessageNotificationType;
use support\Log;
use think\facade\Validate;

/**
 * 经销商逻辑层
 */
class MessageNotificationLogic extends BaseLogic
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new MessageNotification();
    }

    public function getTypeList()
    {
        return MessageNotificationType::column('id, name');
    }


    /**
     * 添加数据
     * @param $data
     * @return mixed
     */
    public function add($data): mixed
    {
        if (!empty($data['company_id'])) {
            $companyIds = $data['company_id'];
        } else {
            $companyIds = Company::where('status', 1)->column('id');
        }

        try {
            $this->transaction(function () use ($companyIds, $data) {
                unset($data['company_id']);
                $messageId = $this->model->insertGetId($data);
                $userIds = CompanyUser::whereIn('company_id', $companyIds)->column('id');

                $relData = [];
                $readData = [];
                foreach ($userIds as $userId) {
                    $readData[] = [
                        'message_notification_id' => $messageId,
                        'user_id' => $userId,
                    ];
                }
                MessageNotificationRead::insertAll($readData);

                foreach ($companyIds as $companyId) {
                    $relData[] = [
                        'notification_id' => $messageId,
                        'company_id' => $companyId,
                    ];
                }
                (new MessageNotificationCompany())->saveAll($relData);
            });
            return true;
        } catch (\Exception $e) {
            Log::error('运营消息新增失败：' . $e->getMessage());
            throw new ApiException('运营消息新增失败');
        }
    }
    
    /**
     * 修改数据
     * @param $id
     * @param $data
     * @return mixed
     */
    public function edit($id, $data): mixed
    {
        if (empty($id)) {
            throw new ApiException('数据不存在');
        }
        $row = $this->model->findOrEmpty($id);
        if ($row->isEmpty()) {
            throw new ApiException('数据不存在');
        }

        if (!empty($data['company_id'])) {
            $companyIds = $data['company_id'];
        } else {
            $companyIds = Company::where('status', 1)->column('id');
        }

        try {
            $this->transaction(function () use ($companyIds, $data, $row) {
                unset($data['company_id']);
                // 先删除旧的关联关系，再新增
                (new MessageNotificationCompany())->where('notification_id', $row->id)->delete();
                $row->save($data);
                $relData = [];
                foreach ($companyIds as $companyId) {
                    $relData[] = [
                        'notification_id' => $row->id,
                        'company_id' => $companyId,
                    ];
                }
                (new MessageNotificationCompany())->saveAll($relData);
            });
            return true;
        } catch (\Exception $e) {
            Log::error('运营消息更新失败：' . $e->getMessage());
            throw new ApiException('运营消息更新失败');
        }
    }

}
